package com.zsr.web;

import com.google.gson.Gson;
import com.zsr.pojo.User;
import com.zsr.service.UserService;
import com.zsr.service.impl.UserServiceImpl;
import com.zsr.utils.WebUtils;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

public class UserServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();


    /**
     * 登录方法
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User UModel=userService.login(new User(null, username, password, null));
        if (UModel == null) {

            req.setAttribute("msg", "用户名或密码错误");
            req.setAttribute("username", username);
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req, resp);
        } else {
            System.out.println("登录成功");
            //Cookie记住登录名
            Cookie userName_Cookie=new Cookie("username",username);
            userName_Cookie.setMaxAge(60*60*24*7);
//            userName_Cookie.setPath(getServletContext().getAttribute("basePath").toString());
            resp.addCookie(userName_Cookie);
            // Session保存用户
            req.getSession().setAttribute("user",UModel);

            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req, resp);

        }
    }

    /**
     * 注册方法
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        String username = req.getParameter("username");
//        String password = req.getParameter("password");
          String code = req.getParameter("code");
//        String email = req.getParameter("email");



        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            System.out.println(entry.getKey() + " = " + Arrays.asList(entry.getValue()));
        }

        User user  = WebUtils.copyParamToBean(parameterMap, new User());

        //1.获取谷歌验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //2.清除Session中的验证码
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);


        //2.检查验证码
        if (token.equalsIgnoreCase(code)) {
            //3.检查 用户名是否可用
            if (userService.existsUsername(user.getUsername())) {
                System.out.println("用户名[" + user.getUsername() + "]已存在！");

                req.setAttribute("msg", "用户名[" + user.getUsername() + "]已存在！");
                req.setAttribute("username", user.getUsername());
                req.setAttribute("email", user.getEmail());
                req.setAttribute("code", code);

                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);

            } else {
                userService.registerUser(user);
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req, resp);
            }
        } else {
            System.out.println("验证码错误");

            req.setAttribute("msg", "验证码错误");
            req.setAttribute("username", user.getUsername());
            req.setAttribute("email", user.getEmail());
            req.setAttribute("code", code);

            //获取请求转发器对象，该转发器的指向通过getRequestDisPatcher()的参数设置
            //调用forward()方法，转发请求
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req, resp);
        }
    }

    /**
     * 退出登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.销毁Session
        req.getSession().invalidate();
        //2.重定向到登录页面
        resp.sendRedirect(req.getContextPath()+"/pages/user/login.jsp");
    }

    /**
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
            IOException {
        //获取请求的参数
        String username=req.getParameter("username");
        boolean isExistsUsername = userService.existsUsername(username);
        //把返回的结果封装成map对象
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("existsUsername",isExistsUsername);

        Gson gson = new Gson();
        String json = gson.toJson(resultMap);

        resp.getWriter().write(json);
    }
}
